# import socket and select module

import socket, select, MySQLdb


# define checkData function that is the core of our Socket comunication
def checkData():
    # create an infinitive loop to check data from an AIR client to another one
    while True:
        # use select module to allow an application to wait for input from multiple sockets at a time
        inputready,outputready,exceptready = select.select(input,[],[])
        for s in inputready:
            if s == theSock:
                # add a client to the socket connection
                client, address = theSock.accept()
                input.append(client)
            else:
                # comunication between client and server: manage traffic data
                data = s.recv(1024)
                # in tempConn we put all client without server connection
                tempConn = input[1:len(input)]
                print "socket : ", s, "\n", "msg : ", data
                if data:
                    for i in tempConn:
                        # send to all client any messages
                        i.send(str(i.getsockname()[0]) + ": " + data)
                else:
                    client.close()


# define checkDB function that allows to make a db connection and to retrieve information
def checkLogin(login, pwd):
    try:
        db = MySQLdb.connect("Localhost", "root", "beep", "test")
        cursor = db.cursor()
        sql = """SELECT * FROM users"""
        cursor.execute(sql)
        data = cursor.fetchone()
        print "pseudo : ", data[1], "pass : ", data[2]
        cursor.close()
        db.close()
    except MySQLdb.Error, e:
        print "Error %d: %s" % (e.args[0], e.args[1])
        exit (1)

#define socket connection: address, port and type of socket connection
theAddress = ('localhost', 18000)
theSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
theSock.bind(theAddress)
theSock.listen(5)

input = [theSock]
#after established XMLSocket connection, manage messages from client
checkData()